package eu.jk.web.tag;


import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTag;
import javax.servlet.jsp.tagext.BodyTagSupport;

import eu.jk.performance.buffer.BufferFactory;
import eu.jk.performance.buffer.BufferPool;

public class Cache extends BodyTagSupport {

	Boolean update=false;
	String key=null;
	Boolean global=false;
	
	private boolean buffer=false;
	private String bk;
	private static final long serialVersionUID = 7923066072371460324L;
 
	BufferPool<String> bp = null;

	public Cache() {
		bp = new BufferFactory<String>().newBufferPool(
				"org.eu.http.tag.cache.bufferPool", 256, true);
	}
	
	@Override
	public int doAfterBody() throws JspException {
		buffer=false;
		bp.put(bk, getBodyContent().getString());
		return super.doAfterBody();
	}

	@Override
	public int doEndTag() throws JspException {
		String content=null;
		if(buffer){
			content= bp.get(bk);
		}else{
			content=bodyContent.getString();
		}
		try {
			pageContext.getOut().print(content);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return super.doEndTag();
	}

	@Override
	public int doStartTag() throws JspException {
		buffer=true;
		if(!global)
			bk=((HttpServletRequest)pageContext.getRequest()).getRequestURI()+"/"+key;
		else
			bk="buffer/global/"+key;
		if(bp.contains(bk)&&update!=true){
			return BodyTag.SKIP_BODY;
		}
		return BodyTag.EVAL_BODY_BUFFERED;
	}

	/**
	 * @return the update
	 */
	public Boolean getUpdate() {
		return update;
	}

	/**
	 * @param update the update to set
	 */
	public void setUpdate(Boolean update) {
		this.update = update;
	}

	/**
	 * @return the key
	 */
	public String getKey() {
		return key;
	}

	/**
	 * @param key the key to set
	 */
	public void setKey(String key) {
		this.key = key;
	}

	/**
	 * @return the global
	 */
	public Boolean getGlobal() {
		return global;
	}

	/**
	 * @param global the global to set
	 */
	public void setGlobal(Boolean global) {
		this.global = global;
	}

}
